<?php

namespace app\wxapp\service;

use app\common\model\Colloquial;
use app\common\model\VideoList;
use app\common\youdao\Assess;
use think\facade\Db;

class VideoService
{

    /**
     * 分析语音
     * @param $videoId
     * @param $sentenceId
     * @param $uid
     * @param $text
     * @return bool|mixed
     * @throws \Exception
     */
    public function assess($videoId, $sentenceId, $uid, $text)
    {
        $video = VideoList::where(['id' => $videoId])->find();
        $outVideoId = $video['out_video_id'];

        $exist = Colloquial::where(['uid' => $uid, 'out_video_id' => $outVideoId, 'sentence_id' => $sentenceId])->find();
        if (empty($exist)) {
            throw new \Exception("没有找到录音");
        }
        $path = public_path() . "uploads/kouyulianxi/{$videoId}/{$outVideoId}_{$uid}_{$sentenceId}.wav";

        $assess = new Assess();
        $result = $assess->doAssess($path, $text);
        Colloquial::update(['assess' => json_encode($result)], ['uid' => $uid, 'out_video_id' => $outVideoId, 'sentence_id' => $sentenceId]);
        return $result;
    }

    /**
     * 我的读音 和 总读音
     * @param $videoId
     * @param $sentenceId int
     * @param $uid
     * @return mixed
     */
    public function voiceBaseInfo($videoId, $sentenceId, $uid)
    {
        $video = VideoList::where(['id' => $videoId])->find();
        $outVideoId = $video['out_video_id'];

        $myVoice = Colloquial::where(['uid' => $uid, 'out_video_id' => $outVideoId, 'sentence_id' => $sentenceId])->find();
        $myVoice['assess'] = json_decode($myVoice['assess']) ?: null;

        $total = Colloquial::where(['out_video_id' => $outVideoId, 'sentence_id' => $sentenceId])->count();

        return [
            'myvoice' => $myVoice,
            'total' => $total,
            'domain' => env('aliyun.ali_oss_bucket_domain'),
        ];
    }

    public function voiceList($videoId, $sentenceId, $page, $pageSize)
    {
        $start = ($page - 1) * $pageSize;
        $video = VideoList::where(['id' => $videoId])->find();
        $outVideoId = $video['out_video_id'];

        $voiceList = Colloquial::where(['out_video_id' => $outVideoId, 'sentence_id' => $sentenceId])->limit($start, $pageSize)->select();
        $uids = [];
        foreach ($voiceList as $key => $val) {
            array_push($uids, $val['uid']);
//            $voiceList[$key]['create_time'] = date("m-d H:i",$val['create_time']);
//            $voiceList[$key]['update_time'] = date('m-d H:i',$val['update_time']);
        }
        $wechatUser = Db::table("wechat_user")->whereIn('id', $uids)->column("id,nick_name,avatar_url", 'id');
        foreach ($voiceList as $key => &$val) {
            $val['path'] = env('aliyun.ali_oss_bucket_domain') . $val['path'];
            $val['user'] = $wechatUser[$val['uid']];
        }
        return $voiceList;
    }
}